package com.ifast.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Calendar;
import java.util.UUID;

public class FileUtil {
	public static String DEFAULT_MIME_TYPE = "application/octet-stream";
	/* EXCEL模板保存路径 */
	public static final String TYPE_EXCEL_MODEL = ".xls";
	private static final String PATH_EXCEL_MODEL = "classpath:static/templet/";
//	private static final String PATH_EXCEL_MODEL2 = "static/templet/";
	/**
	 * 获取子目录
	 * @return
	 */
	public static String getChildDir(){
		Calendar cal = Calendar.getInstance();
		String child;
		if(Calendar.MONTH < 9){
			child = String.valueOf(cal.get(Calendar.YEAR))+"0"+String.valueOf(cal.get(Calendar.MONTH)+1);
		}else{
			child = String.valueOf(cal.get(Calendar.YEAR))+String.valueOf(cal.get(Calendar.MONTH)+1);
		}

		return child;
	}

	public static String getFileSufix(String fileName) {
		int splitIndex = fileName.lastIndexOf(".");
		return fileName.substring(splitIndex + 1);
	}

	public static String getSuffix(String filename) {
		String result = "";
		if (filename.indexOf(".") != -1) {
			result = filename.substring(filename.lastIndexOf("."));
		}
		return result;
	}


	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}


	public static File fetchExcelModelFile(String filename) throws IOException {
		File file = null;
		//Method 1
		file = ResourceUtils.getFile(PATH_EXCEL_MODEL + filename + TYPE_EXCEL_MODEL);

		//Mehtod 2
//		Resource resouce = new ClassPathResource(PATH_EXCEL_MODEL2 + filename + TYPE_EXCEL_MODEL);
//		file = resouce.getFile();


		//Method 3
//		File path = new File(ResourceUtils.getURL("classpath:").getPath());
//		file = new File(path.getAbsolutePath(),PATH_EXCEL_MODEL2 + filename + TYPE_EXCEL_MODEL);


		return file;
	}

	public static String getMineType(ServletContext context, String fileName) {
		String type = "";
		if (StringUtils.isNotBlank(fileName)) {
			type = context.getMimeType(fileName.toLowerCase());
			if (type == null)
				type = DEFAULT_MIME_TYPE;
		} else {
			type = DEFAULT_MIME_TYPE;
		}
		return type;
	}

}
